import { getToken, setToken, removeToken } from '@/utils/auth'
import router, { resetRouter } from '@/router'
import { SYS_LOGIN_API,SYS_USER_API } from '@/api/systemApi.js'

const getDefaultState = () => {
  return {
   name: '',
   groupId:'',
   paths:[]
  }
}

const state = getDefaultState()

const mutations = {
  RESET_STATE: (state) => {
    Object.assign(state, getDefaultState())
  },
  SET_NAME: (state, name) => {
    state.name = name
  },
  SET_PATHS: (state, paths) => {
    state.paths = paths
  },
  SET_GROUP_ID: (state, groupId) => {
    state.groupId = groupId
  },
}

const actions = {
  // user login
  login({ commit }, userInfo) {
    const { username, password } = userInfo
    return new Promise((resolve, reject) => {
      SYS_LOGIN_API.loginWeb({ username: username.trim(), password: password.trim() }).then(response => {
        const token = response.data
        setToken(token)
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },

  // get user info
  getInfo({ commit, state }) {
    return new Promise((resolve, reject) => {
      SYS_USER_API.getCurrentUser().then(response => {
        const { data } = response
        if (!data) {
          reject('校验用户失败，请重新登录.')
        }
        const { nickname, paths, groupId } = data
        commit('SET_NAME', nickname)
        commit('SET_PATHS', paths)
        commit('SET_GROUP_ID', groupId)
        resolve(data)
      }).catch(error => {
        reject(error)
      })
    })
  },

  // user logout
  logout({ commit, state, dispatch }) {
    return new Promise((resolve, reject) => {
      try{
        commit('RESET_STATE')
        removeToken()
        resetRouter()

        // reset visited views and cached views
        // to fixed https://github.com/PanJiaChen/vue-element-admin/issues/2485
        dispatch('tagsView/delAllViews', null, { root: true })

        resolve()
      }catch(e){
        reject(e)
      }
    })
  },

  // remove token
  resetToken({ commit }) {
    return new Promise(resolve => {
      commit('RESET_STATE')
      removeToken()
      resetRouter()
      resolve()
    })
  },

}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
